/* eslint-disable no-magic-numbers */
/*
 * @Date: 2022-04-07 18:44:59
 * @LastEditors: zhaoxm
 * @LastEditTime: 2022-08-31 18:48:05
 * @Description: 限制输入框 输入金额 过滤其他字符指令
 */

import Vue from "vue"

Vue.directive("enterMoney", {
  bind(element, { value = 2 }) {
    element = element.nodeName === "INPUT" ? element : element.children[0]
    const RegString =
      value === 0
        ? "^[\\+\\-]?\\d+\\d{0,0}"
        : `^[\\+\\-]?\\d+\\.?\\d{0,${value}}`

    element.addEventListener("input", () => {
      element.value = element.value.match(new RegExp(RegString, "g"))
      element.value = !element.value.includes(".") ? element.value.slice(0, 10) : element.value.slice(0, 13)
    })
      
    element.addEventListener("keyup", () => {
      element.value = element.value.match(new RegExp(RegString, "g"))
      element.value = !element.value.includes(".") ? element.value.slice(0, 10) : element.value.slice(0, 13)
      element.dispatchEvent(new Event("input"))
    })
    element.addEventListener("blur", () => {
      if (!element.value) return
      element.value = Number(element.value).toFixed(2)
      element.dispatchEvent(new Event("input"))
    })
  },
})
